# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


from typing import *


class Solution:
    def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        q = [[root]]
        level = 0
        while len(q) > 0:
            p = []
            s = 0
            for nodes in q:
                for node in nodes:
                    s += node.val
                    nxt = []
                    if node.left:
                        nxt.append(node.left)
                    if node.right:
                        nxt.append(node.right)
                    if len(nxt) > 0:
                        p.append(nxt)
            for nodes in q:
                if level < 1:
                    for node in nodes:
                        node.val = 0
                else:
                    t = 0
                    for node in nodes:
                        t += node.val
                    for node in nodes:
                        node.val = s - t
            level += 1
            q = p

        return root
